// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using SnapObjects.Commons;

namespace SnapObjects.Data
{
    internal class DefaultSortTokenizer : IEnumerable<string>, IEnumerator<string>, IDisposable
    {
        private readonly string _expression;
        private CharacterReader _character;

        public DefaultSortTokenizer(string expression)
        {
            _expression = expression;

            _character = new CharacterReader(expression);
        }

        public string Current { get; private set; }

        object IEnumerator.Current => this.Current;

        public void Dispose()
        {
            _character.Dispose();
        }

        public bool MoveNext()
        {
            var builder = new StringBuilder();

            while (_character.Read())
            {
                if (_character.Current == ' '
                    || _character.Current == ','
                    || _character.Current == '('
                    || _character.Current == ')')
                {
                    if (builder.Length == 0)
                    {
                        builder.Append(_character.Current);
                    }
                    else
                    {
                        _character.Putback();
                    }
                    break;
                }
                else
                {
                    builder.Append(_character.Current);
                }
            }

            this.Current = builder.ToString();

            return builder.Length > 0;
        }

        public void Reset()
        {
            if (_character != null)
            {
                _character.Dispose();
                _character = null;
            }

            _character = new CharacterReader(_expression);
        }

        public IEnumerator<string> GetEnumerator()
        {
            return this;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this;
        }
    }
}
